<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/6/4
 * Time: 13:23
 */

namespace app\admin\controller\shop;

use app\admin\BaseController;
use app\admin\model\ProductGroupRelation;
use app\lib\exception\FailedException;
use app\lib\exception\NoJurisdiction;
use app\lib\exception\NotFoundException;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\ShopGroupValidate;
use app\Validate\UpdateOrDeleteGroupValidate;
use think\Request;
use app\admin\model\ShopGroup as ShopGroupModel;

class ShopGroup extends BaseController {
    /**
     * 创建商品分组
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     * @throws NoJurisdiction
     */
    public function createShopGroup(Request $request){
        (new ShopGroupValidate( ))->goCheck();
        $groupInfo = $request->post();
        $admin = $this->admin;
        if($admin['account_type']==2){//如果是商家账号
            if($groupInfo['uid']!=$admin['uid']){ throw new NoJurisdiction(); }
        }
        $result = (new ShopGroupModel()) ->save($groupInfo);
        if($result){
            return writeJson(200,[]);
        }else{
            throw new FailedException([ 'msg' => '新增'.$groupInfo['group_name'].'失败']);
        }
    }

    /**
     * 获取商品分组
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws NoJurisdiction
     * @throws FailedException
     */
    public function shopGroupList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $admin = $this->admin;
        if($admin['account_type']==1 && $post['uid'] == 0){ throw new FailedException(['msg'=>'缺少商家账号']); }
        if($admin['account_type']==2 && $post['uid'] != $admin['uid']){ throw new NoJurisdiction(); }

        $where = [];
        $where[] = ['uid','eq',$post['uid']];
        if(isset($post['group_name'])&&$post['group_name']!=""){
            $where[] = ['group_name','like','%'.$post['group_name'].'%'];
        }
        $count = (new \app\admin\model\ShopGroup())->getCount($where);
        $where['page'] = $post['page'];
        $existGroup = (new \app\admin\model\ShopGroup())->wechatList($where,"*","sort desc",$post['page_number']);

        //添加默认分组
        if(Count($existGroup) == 0){ $existGroup[0] = $this->addDefaultGroup($admin['uid']); }
        foreach ($existGroup as $key=>$value){
            $existGroup[$key]['product_number'] = (new \app\admin\model\ProductGroupRelation())->where([['group_id','eq',$value['id']]])->count();
        }

        return writeJson(200,['dataList'=>$existGroup,'count'=>$count]);
    }

    /**
     * 根据主键ID更新分组
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateShopGroup(Request $request){
        (new UpdateOrDeleteGroupValidate())->goCheck();
        $shopGroupModel = new ShopGroupModel();
        $updateInfo  = $request->post();
        $existGroupInfo = ShopGroupModel::findGroupListById($updateInfo['id']);
        if(empty($existGroupInfo->toArray())){
            throw new NotFoundException([ 'msg' => '该分类不存在']);
        }else{
            $result = $shopGroupModel->save(['group_name'=>$updateInfo['group_name']],['id'=>$updateInfo['id']]);
            if(!$result){ throw new FailedException(['msg' => '更新分组失败，请重试']); }
            return writeJson(200,[]);
        }
    }

    /**
     * 根据主键ID删除分组
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deleteShopGroup(Request $request){
        (new IdMustPositive())->goCheck();
        $id = $request->param('id');
        //判断分组下面是否有商品 有商品则不能删除分组
        $count = (new ProductGroupRelation())->where('group_id',$id)->count();
        if($count > 0){ throw new NotFoundException(['msg' => '分组下面有商品不能删除']);}
        $existGroup = ShopGroupModel::findGroupListById($id);
        if(empty($existGroup->toArray())){
            throw new NotFoundException(['msg' => '该分类不存在']);
        }else{
            $result = (new ShopGroupModel())->SoftDelete(['id'=>$id]);
            if(!$result){ throw new FailedException(['msg' => '删除分类失败']);}
            return writeJson('200',[],'删除成功');
        }
    }

    /**
     * 新增默认分组
     * @param $uid
     * @return array
     */
    private function addDefaultGroup($uid){
        $groupInfo = [];
        $groupInfo["uid"] = $uid;
        $groupInfo["group_name"] = "默认分组";
        $groupInfo["sort"] = 99;
        (new ShopGroupModel()) ->save($groupInfo);
        $groupInfo["id"] = (new ShopGroupModel())->getLastInsID();
        return $groupInfo;
    }
}